import React, { useState, useEffect } from 'react';
//在线作图对话框 2022-4-18
import dayjs from 'dayjs';
import DialogSimple from './DialogSimple';

import {Table , Form, Button } from 'react-bootstrap' ;

//onOk
//onCancel
//isOpen
//lyrParamsGroup
//onSelectROIClick
//appCurrentROI
//selectedROI
//loginedUser 
//openlayerRef
//props.onSelectTemplateClick
//props.templateObj
//props.appDateA
//props.appDateB
function DialogSimpleOmc(props) {

    const [dataLayerArray, setDataLayerArray] = useState([]) ;
    const [roiObject, setRoiObject] = useState(null);
    const [selectedDataLayerIndex, setSelectedDataLayerIndex] = useState(0) ;
    const [isBusy, setIsBusy] = useState(false);
    const [templateObj, setTemplateObj] = useState(null) ;
    const [isAutoZoom, setIsAutoZoom] = useState(false) ;


    useEffect(() => {
        setTemplateObj(props.templateObj) ;
    }, [props.templateObj])
    
    
    useEffect(() => {
        let lyr1 = null;
        let index = 0;
        let datalyrArr = [];
        for (lyr1 of props.lyrParamsGroup) {
            if (
                lyr1.productDisplay.type === 'pe'
                || lyr1.productDisplay.type === 'ud'
            ) {
                datalyrArr.push(lyr1);
            } else if (
                lyr1.productDisplay.type === 'pes'
                || lyr1.productDisplay.type === 'us'
            ) {
                datalyrArr.push(lyr1);
            }
        }
        setDataLayerArray(datalyrArr);

        if( props.selectedROI!==null ){
            setRoiObject(props.selectedROI) ;
        }
    }, [props.isOpen, props.lyrParamsGroup,props.selectedROI])


    const onCurrentROIClick = function () {
        setRoiObject(props.appCurrentROI);
    }

    const onClearROIClick = function () {
        setRoiObject(null);
    }

    //js Date 对象转Long型 YYYYMMDD000000 数据，注意目前时分秒使用0代替。
	const convertJsDate2Ymd14 = function (jsDate) {
		const dayjsdate = dayjs(jsDate);
		const datetime1 = dayjsdate.format("YYYYMMDD000000");
		return datetime1;
	}



    const onOk = function () {

        if( dataLayerArray.length===0 ) return ;
        if( selectedDataLayerIndex < 0  ){
            return ;
        }
        // if( roiObject===null || roiObject.rid===0 ){
        //     return ;
        // }

        let pid = 0 ;
        let sid = 0 ;
        let selectedDataLayer = dataLayerArray[selectedDataLayerIndex] ;
        if (
            selectedDataLayer.productDisplay.type === 'pe'
            || selectedDataLayer.productDisplay.type === 'ud'
        ) {
            pid = selectedDataLayer.pid ;
        } else if (
            selectedDataLayer.productDisplay.type === 'pes'
            || selectedDataLayer.productDisplay.type === 'us'
        ) {
            const tempObj = JSON.parse(selectedDataLayer.productDisplay.params) ;
            sid = tempObj.sid ;
        }else{
            // xyz wms pgm do nothing
            return ;
        }
        
        let roiid = "null" ;
        if( roiObject!==null && roiObject.rid!==0 ){
            roiid = "sys:" + roiObject.rid ;
            if( roiObject.uid>0) roiid = "user:" + roiObject.rid ;
        }
        

        let datetime1 =  convertJsDate2Ymd14(props.appDateA);//2022-7-22
        let styleid1 =  selectedDataLayer.styleid ;
        let sdui1 = 'null';// selectedDataLayer.sdui ;
        if( typeof selectedDataLayer.sdui !== 'undefined' && selectedDataLayer.sdui!==null )
        {
            let slimSdui = {};
            for (let key in selectedDataLayer.sdui ) {
                slimSdui[key] = { val: selectedDataLayer.sdui[key].val };
            }
            sdui1 = JSON.stringify(slimSdui) ;
        }
        let uid1 = props.loginedUser.uid ;

        const formData = new FormData();
        formData.append('uid' , uid1) ;
        formData.append('datetime', datetime1 ); 
        formData.append('styleid',  styleid1 );
        formData.append('sdui',     sdui1 );
        formData.append('pid',      pid );
        formData.append('sid',      sid );
        formData.append('roiid',    roiid );
        setIsBusy(true) ;
        let url = global.g_serverAPIRoot + "omc/newqgs" ;
        if( templateObj !== null ){
            url = global.g_serverAPIRoot + "omc/newfromtem" ;
            formData.append("temfile", templateObj.file ) ;
            formData.append("isautozoom", (isAutoZoom===true)?1:0  ) ;
            const olextent = props.openlayerRef.current.getMapExtent() ;
            let x0 = Math.max(-180, olextent[0]) ;
            let y0 = Math.max(-90, olextent[1]) ;
            let x1 = Math.min(180, olextent[2]) ;
            let y1 = Math.min(90, olextent[3]) ;
            formData.append("left" , x0 ) ;
            formData.append("right", x1 ) ;
            formData.append("top"  , y1 ) ;
            formData.append("bottom", y0 ) ;
        }

        fetch(
            url,
            {
                method: 'POST',
                body: formData,
            }
        )
        .then((response) => response.json())
        .then((result) => {
            
            if( result.state===0 ){
                //good
                setIsBusy(false) ;
                props.onOk();
                setTemplateObj(null) ;
                setIsAutoZoom(false) ;
                setSelectedDataLayerIndex(0) ;
                setRoiObject(null);
                setDataLayerArray([]) ;
                const olextent = props.openlayerRef.current.getMapExtent() ;
                let x0 = Math.max(-180, olextent[0]) ;
                let y0 = Math.max(-90, olextent[1]) ;
                let x1 = Math.min(180, olextent[2]) ;
                let y1 = Math.min(90, olextent[3]) ;
                
                const url1 = global.g_omcindexpageurl+"?file="+result.data
                +"&x0="+x0.toFixed(5)+"&y0="+y0.toFixed(5)
                +"&x1="+x1.toFixed(5)+"&y1="+y1.toFixed(5) 
                + "&uid=" + uid1 ;
                window.open(url1, "_blank") ;
            }else{
                //bad
                setIsBusy(false) ;
                alert(result.message) ;
            }
        }).catch(err=> {
            setIsBusy(false) ;
            console.log(err) ;// 505 404 ... errors
        })      
        ;
    }

    const onCancel = function () {
        //reset all
        setTemplateObj(null) ;
        setIsAutoZoom(false);
        setDataLayerArray([]);
        setRoiObject(null);
        setSelectedDataLayerIndex(0) ;
        props.onCancel();
    }

    const onSelectDataLayerChanged = function(ev){
        setSelectedDataLayerIndex( parseInt(ev.target.value) ) ;
    }

    const onDirectlyOpenOMCClick = function() {
        props.onOk();
        let uid1 = props.loginedUser.uid ;
        const url1 = global.g_omcindexpageurl+"?" + "uid=" + uid1 ;
        window.open(url1, "_blank") ;
    }

    const onSelectTemplateClick = function() {
        props.onSelectTemplateClick() ;
    }

    const onClearTemplateClick = function() {
        setTemplateObj(null) ;
    }


    const onAutoZoomChanged = function(ev){
        console.log(ev) ;
        console.log(ev.target.checked) ;
        setIsAutoZoom(ev.target.checked) ;
    }



    const renderContent = function () {
        return (
            <div style={{ margin: 'auto', marginTop: '8px'   }}>
                <Form >
                    <Table >
                        <tbody>
                            <tr>
                                <td></td>
                                <td style={{textAlign:'left'}}>
                                <Button size='sm' variant="success" onClick={onDirectlyOpenOMCClick}>直接打开制图功能</Button>
                                </td>                             
                            </tr>
                            <tr>
                                <td>
                                    数据图层:
                                </td>
                                <td style={{textAlign:'left'}}>
                                    <select 
                                    style={{width:'240px'}}
                                    onChange={onSelectDataLayerChanged}
                                    value={selectedDataLayerIndex}
                                    >
                                        {
                                            dataLayerArray.map((item,index) => (
                                                <option key={'k-'+index} 
                                                value={index}>
                                                    {item.productDisplay.productname}
                                                    </option>
                                            ))
                                        }
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    感兴趣区:
                                </td>
                                <td style={{textAlign:'left'}}>
                                    <Form.Control placeholder='请选择感兴趣区' type="text" style={{ width: '240px' }} disabled size='sm'
                                        value={(roiObject !== null) ? roiObject.name : ""}
                                    />
                                </td>
                            </tr>
                            <tr>
                                <td>

                                </td>
                                <td>
                                    <Button size='sm' variant="success" 
                                    style={{marginRight:'8px'}}
                                    onClick={onCurrentROIClick}>当前ROI</Button>
                                    <Button size='sm' variant="secondary" 
                                    style={{marginRight:'8px'}}
                                    onClick={props.onSelectROIClick}>选择ROI</Button>
                                    <Button size='sm' variant="warning" 
                                    onClick={onClearROIClick}>清除ROI</Button>
                                    
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    当前作图模板:
                                </td>
                                <td style={{textAlign:'left'}}>
                                    {
                                       (typeof templateObj ==='undefined' 
                                       || templateObj === null )?(
                                        <>不使用作图模板。</>
                                        ):(
                                            <>
                                            <img 
                                            style={{
                                                width:"100px",
                                                height:"100px",
                                                border:"1px solid gray",
                                                objectFit:"contain"
                                            }}
                                            src={global.g_staticResourceRoot+templateObj.file+".thumb.png"}
                                            />
                                            <p>{templateObj.name}</p>
                                            </>
                                        ) 
                                    }
                                </td>
                            </tr>
                            <tr>
                                <td>
                                </td>
                                <td style={{textAlign:'left'}}>
                                    <Button size='sm' 
                                    style={{marginRight:'8px'}}
                                    variant="secondary" 
                                    onClick={onSelectTemplateClick}>选择绘图模板</Button>
                                    <Button size='sm' 
                                    variant="warning" 
                                    onClick={onClearTemplateClick}>清除绘图模板</Button>
                                </td>
                            </tr>
                            {
                                (typeof templateObj !=='undefined' 
                                && templateObj !== null )?(
                                    <tr>
                                        <td>
                                        缩放到当前:
                                        </td>
                                        <td style={{textAlign:'left'}}>
                                            <input type="checkbox" 
                                            checked={isAutoZoom} 
                                            onChange={onAutoZoomChanged} />
                                        </td>
                                    </tr>
                                ):""
                            }
                        </tbody>
                    </Table>
                </Form>
                {
                    (isBusy)?<div class="ui active centered inline loader"></div>:""
                }
                
            </div>
        );
    }


    return <DialogSimple
        isOpen={props.isOpen}
        onCancel={onCancel}
        dialogTitle={"在线作图"}
        onOk={onOk}
        renderContent={renderContent}
    />;
}

export default DialogSimpleOmc